import chalk from 'chalk';
import {
	sizeFormat,
	timeFormat,
} from './format.js';

export default function({buildConsole}){
	return function(err,stats){
		//region 错误处理
		if(err){
			console.error(err.stack||err);
			if(err.details){
				console.error(err.details);
			}
			return;
		}
		const info=stats.toJson();
		if(stats.hasWarnings()){
			for(const warn of info.warnings){
				console.log(warn.message);
			}
		}
		if(stats.hasErrors()){
			for(const error of info.errors){
				console.log(error.message);
			}
			return;
		}
		//endregion
		//region 信息报告
		if(buildConsole==='raw'){
			console.log(stats.toString({
				colors:true,
			}));
		}else if(buildConsole==='normal'){
			let jsSize=0;
			let jsStr='';
			let cssSize=0;
			let cssStr='';
			let otherSize=0;
			let otherStr='';
			for(const {name,size} of info.assets){
				if(name.endsWith('.js')){
					jsSize+=size;
					jsStr+=`  ${chalk.green(name.padEnd(60))}  ${sizeFormat(size)}\n`;
				}else if(name.endsWith('.css')){
					cssSize+=size;
					cssStr+=`  ${chalk.green(name.padEnd(60))}  ${sizeFormat(size)}\n`;
				}else{
					otherSize+=size;
					otherStr+=`  ${chalk.green(name.padEnd(60))}  ${sizeFormat(size)}\n`;
				}
			}
			jsStr=jsStr.slice(0,-1)
			cssStr=cssStr.slice(0,-1)
			otherStr=otherStr.slice(0,-1)
			let entry='';
			for(const [key,{assetsSize,assets}] of Object.entries(info.entrypoints)){
				entry+=`\n  ${chalk.red(key)}: ${chalk.blue(sizeFormat(assetsSize))}\n`+assets.map(({name,size}) => {
					return `    ${chalk.green(name.padEnd(58))}  ${sizeFormat(size)}`;
				}).join('\n');
			}
			console.log(`
js总大小: ${chalk.blue(sizeFormat(jsSize))}
${jsStr}
css总大小: ${chalk.blue(sizeFormat(cssSize))}
${cssStr}
其他资源总大小: ${chalk.blue(sizeFormat(otherSize))}
${otherStr}
入口:${entry}

webpack版本: ${chalk.blue(info.version)}, 包大小: ${chalk.blue(sizeFormat(jsSize+cssSize+otherSize))}, 编译时间: ${chalk.blue(timeFormat(info.time))}
`);
		}
		//endregion
	};
};
